package com.boe.common.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

public class FileUtil {
    public static String joinPath(String... path) {
        if (path.length == 0) return "";

        var firstPath = path[0];
        var isRoot = firstPath.startsWith("/") || firstPath.startsWith("\\");

        var list = new ArrayList<String>();


        var splitList = Arrays.asList(path).stream()
                .map(it -> {
                            return Arrays.asList(it.split("[\\|/]"));
                        }
                ).collect(Collectors.toList());

        var spreadList = ListUtil.<String>unwind(splitList).stream()
                .filter(it -> !it.isEmpty())
                .filter(it -> !it.equals("."))
                .toList();


        for (var i = 0; i < spreadList.size(); i++) {
            var it = spreadList.get(i);
            if (Objects.equals(it, "..")) {
                if (ListUtil.removeLast(list) == null) {
                    throw new RuntimeException("路径层级溢出");
                }
                continue;
            }

            list.add(it);
        }


        if (isRoot) {
            return File.separator + String.join(File.separator, list);
        }

        return String.join(File.separator, list);
    }
}
